<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />





  <link rel="alternate" href="/atom.xml" title="尛孟的博客" type="application/atom+xml" />






<meta name="description" content="前言:   由于查询数据库时查询条件需要传递日期来获取某个月份的数据列表,如果传的时该月的某一天会导致拿到数据不全,如果传了该月的第一天会导致拿到的数据并不是当月的;而如果刚好查询当前月份的数据是不能用这个月的最后一天只能用当天来查询,于是有了以下的日历操作   首先,想要直接得到某个日期的NSDate,可以通过dateWithTimeInterval,与某个日期的毫秒差来获取,但是这个方法前提">
<meta property="og:type" content="article">
<meta property="og:title" content="NSdate+NSCalendar操作">
<meta property="og:url" content="http://yoursite.com/2018/01/10/NSdate+NSCalendar操作/index.html">
<meta property="og:site_name" content="尛孟的博客">
<meta property="og:description" content="前言:   由于查询数据库时查询条件需要传递日期来获取某个月份的数据列表,如果传的时该月的某一天会导致拿到数据不全,如果传了该月的第一天会导致拿到的数据并不是当月的;而如果刚好查询当前月份的数据是不能用这个月的最后一天只能用当天来查询,于是有了以下的日历操作   首先,想要直接得到某个日期的NSDate,可以通过dateWithTimeInterval,与某个日期的毫秒差来获取,但是这个方法前提">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-12T13:04:31.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="NSdate+NSCalendar操作">
<meta name="twitter:description" content="前言:   由于查询数据库时查询条件需要传递日期来获取某个月份的数据列表,如果传的时该月的某一天会导致拿到数据不全,如果传了该月的第一天会导致拿到的数据并不是当月的;而如果刚好查询当前月份的数据是不能用这个月的最后一天只能用当天来查询,于是有了以下的日历操作   首先,想要直接得到某个日期的NSDate,可以通过dateWithTimeInterval,与某个日期的毫秒差来获取,但是这个方法前提">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'ZNJ0RM31SP',
      apiKey: '9fae47ade11c769ab25bba4061522c1d',
      indexName: 'for_meng',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":" 找不到关于 ”${query}“ 的文章 ","hits_stats":" 共找到${hits} 篇文章,花了${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/01/10/NSdate+NSCalendar操作/"/>




<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">


  <title>NSdate+NSCalendar操作 | 尛孟的博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">尛孟的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">想法总是无法付诸实践…</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/01/10/NSdate+NSCalendar操作/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="尛孟">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="尛孟的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">NSdate+NSCalendar操作</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-10T14:03:34+08:00">
                2018-01-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/iOSDevelopment/" itemprop="url" rel="index">
                    <span itemprop="name">iOS开发</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/iOSDevelopment/Project-daily/" itemprop="url" rel="index">
                    <span itemprop="name">项目/日常问题</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/01/10/NSdate+NSCalendar操作/" class="leancloud_visitors" data-flag-title="NSdate+NSCalendar操作">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <hr>
<h3 id="前言"><a href="#前言" class="headerlink" title="前言:"></a>前言:</h3><p>   <strong><em>由于查询数据库时查询条件需要传递日期来获取某个月份的数据列表,如果传的时该月的某一天会导致拿到数据不全,如果传了该月的第一天会导致拿到的数据并不是当月的;而如果刚好查询当前月份的数据是不能用这个月的最后一天只能用当天来查询,于是有了以下的日历操作</em></strong></p>
<hr>
<ul>
<li>首先,想要直接得到某个日期的NSDate,可以通过dateWithTimeInterval,与某个日期的毫秒差来获取,但是这个方法前提是需要知道基点日期,就算以当前的Date来计算,毫秒的计算也得自己去写清楚;比较麻烦,这时候可以通过<strong>日历对象的NSDateComponents来方便地定制指定日期,以下是两个NSDate分类方法</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">//这个方法可以获取某个与当前NSDate对象指定间隔的日期</span><br><span class="line">//这里传的year.month 等都可以有正负,正数表示该日期之后的,负数表示该日期之前</span><br><span class="line">- (instancetype)getDateFromDateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day hours:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second&#123;</span><br><span class="line">    //创建一个工具，一个封装了具体年月日、时秒分、周、季度等的类</span><br><span class="line">    //    NSDateComponents* dateComponents = [[NSDateComponents alloc]init];</span><br><span class="line">    NSDateComponents* dateComponents;</span><br><span class="line">    //创建一个日历，它提供了大部分的日期计算接口，并且允许在NSDate和NSDateComponents之间转换</span><br><span class="line">    NSCalendar *dateCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];</span><br><span class="line">  </span><br><span class="line">    // NSDate 转 NSDateComponents所需要设置的值，可根据需要自己设置，这里是年～秒全部获取，如果某个没有写的话，比如NSCalendarUnitHour，转成NSDateComponents后，会是一个很大或很小的数</span><br><span class="line">    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;</span><br><span class="line">    </span><br><span class="line">    //为dateComponents获取值，该值等价于self的各个部件</span><br><span class="line">    dateComponents = [dateCalendar components:unitFlags fromDate:self];</span><br><span class="line">    //创建一个NSDateComponents，开始设置想要的时间</span><br><span class="line">    NSDateComponents *myCompoentes = [[NSDateComponents alloc]init];</span><br><span class="line">    [myCompoentes setYear:dateComponents.year + year];</span><br><span class="line">    [myCompoentes setMonth:dateComponents.month + month];</span><br><span class="line">    [myCompoentes setDay:dateComponents.day + day];</span><br><span class="line">    [myCompoentes setHour:dateComponents.hour + hour];</span><br><span class="line">    [myCompoentes setMinute:dateComponents.minute + minute];</span><br><span class="line">    [myCompoentes setSecond:dateComponents.second + second];</span><br><span class="line">    </span><br><span class="line">    //把通过myCompoentes设置的值转为NSDate格式，这个NSDate就是想要的时间</span><br><span class="line">    NSDate *myDate = [dateCalendar dateFromComponents:myCompoentes];</span><br><span class="line">    </span><br><span class="line">    return myDate;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//这个方法可以直接更改某个日期的某个组件   参数传-1表示不改变</span><br><span class="line">- (instancetype)setDateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day hours:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second&#123;</span><br><span class="line">    //创建一个工具，一个封装了具体年月日、时秒分、周、季度等的类</span><br><span class="line">    NSDateComponents* dateComponents;</span><br><span class="line">    //创建一个日历，它提供了大部分的日期计算接口，并且允许在NSDate和NSDateComponents之间转换</span><br><span class="line">    NSCalendar *dateCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];</span><br><span class="line"></span><br><span class="line">    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;</span><br><span class="line">    </span><br><span class="line">    dateComponents = [dateCalendar components:unitFlags fromDate:self];</span><br><span class="line">    //创建一个NSDateComponents，开始设置想要的时间</span><br><span class="line">    NSDateComponents *myCompoentes = [[NSDateComponents alloc]init];</span><br><span class="line">    </span><br><span class="line">    year != -1 ? [myCompoentes setYear:year] : [myCompoentes setYear:dateComponents.year];</span><br><span class="line">    month != -1 ? [myCompoentes setMonth:month] : [myCompoentes setMonth:dateComponents.month];</span><br><span class="line">    day != -1 ? [myCompoentes setDay:day] : [myCompoentes setDay:dateComponents.day];</span><br><span class="line">    hour != -1 ? [myCompoentes setHour:hour] : [myCompoentes setHour:dateComponents.hour];</span><br><span class="line">    minute != -1 ? [myCompoentes setMinute: minute : [myCompoentes setMinute:dateComponents.minute];</span><br><span class="line">    second != -1 ? [myCompoentes setSecond:second] : [myCompoentes setSecond:dateComponents.second];</span><br><span class="line">    //把通过myCompoentes设置的值转为NSDate格式，这个NSDate就是想要的时间</span><br><span class="line">    NSDate *myDate = [dateCalendar dateFromComponents:myCompoentes];</span><br><span class="line">    </span><br><span class="line">    return myDate;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<ul>
<li>接下来要分析如何得到某个月份的最后一天,由于每个月的天数的不一样,还有2月这个特殊存在,不好使用穷尽判断的方式来设置.这时候就想到<strong>日历对象对日期的操作,结合上面两个方法,轻而易举的就实现了</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">- (NSDate *)getMonthLastDate&#123;</span><br><span class="line">  //先设置为1号,因为比如10月份如果是刚好是31号然后让它月份+1,会导致得到的日期变成12月的1号而不是11月30号</span><br><span class="line">    NSDate *firstDate = [self setDateWithYear:-1 month:-1 day:1 hours:0 minute:0 second:0];</span><br><span class="line">    //再让月份+1  ,这样就得到了下个月的1号</span><br><span class="line">    NSDate *nextMonthDate = [firstDate getDateFromDateWithYear:0 month:1 day:0 hours:0 minute:0 second:0];</span><br><span class="line">    //最后让已经是1号的NSDate天数-1,  就得到了本月的最后一天了</span><br><span class="line">    NSDate *monthLastDate = [nextMonthDate getDateFromDateWithYear:0 month:0 day:-1 hours:0 minute:0 second:0];</span><br><span class="line">    return monthLastDate;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<ul>
<li>这里有个小插曲,就是如果需要拿当前月份的数据的时候,不能传这个月的最后一天,只能传当前Date,因此需要<strong>判断NSDate是否是当月</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">- (BOOL)isThisMonth</span><br><span class="line">&#123;</span><br><span class="line">    NSCalendar *calendar = [NSCalendar currentCalendar];</span><br><span class="line">    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth;</span><br><span class="line">    // 获得某个时间的年月</span><br><span class="line">    NSDateComponents *dateCmps = [calendar components:unit fromDate:self];</span><br><span class="line">  //与当前日期比较</span><br><span class="line">    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];</span><br><span class="line">    return dateCmps.year == nowCmps.year &amp;&amp; dateCmps.month == nowCmps.month;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<ul>
<li><strong>如果需要判断得到的日期是否是周末</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">- (BOOL)isWeekend&#123;</span><br><span class="line">    //计算week数</span><br><span class="line">    NSCalendar * myCalendar = [NSCalendar currentCalendar];</span><br><span class="line">    myCalendar.timeZone = [NSTimeZone systemTimeZone];</span><br><span class="line">    NSInteger week = [[myCalendar components:NSCalendarUnitWeekday fromDate:self] weekday];</span><br><span class="line">    //国际日期中1是周日 7是周六 , 其他2~6对应星期一~星期五</span><br><span class="line">    switch (week) &#123;</span><br><span class="line">        case 1: &#123; return YES; &#125;</span><br><span class="line">        case 7: &#123; return YES; &#125;</span><br><span class="line">        default: &#123; return NO; &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/10/限制键盘输入字符:位数/" rel="next" title="限制键盘输入字符/位数">
                <i class="fa fa-chevron-left"></i> 限制键盘输入字符/位数
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/10/小程序-小程序基本框架/" rel="prev" title="小程序-小程序基本框架">
                小程序-小程序基本框架 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">尛孟</p>
              <p class="site-description motion-element" itemprop="description">与人联系甚少</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言:</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">尛孟</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.4"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("KhsxPkrt4UYiKBnwYFY9zUTN-gzGzoHsz", "a1zezRocQqcmPxlFVdXKrhz9");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
